package com.ruoyi.examation.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.examation.vo.ExamRegistrationVo;
import com.ruoyi.examation.vo.ExamRegistrationDto;
import com.ruoyi.examation.vo.ExamRegistrationUserVo;
import com.ruoyi.examation.service.IExamRegistrationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 考试报名Controller
 *
 * @author Tellsea
 * @date 2025-09-28
 */
@Api(tags = "考试报名Controller")
@RestController
@RequestMapping("/examation/examRegistration")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ExamRegistrationController extends BaseController {

    private final IExamRegistrationService examRegistrationService;

    @ApiOperation("查询考试报名列表")
    @PreAuthorize("@ss.hasPermi('examation:examRegistration:list')")
    @GetMapping("/list")
    public TableDataInfo<ExamRegistrationVo> list(ExamRegistrationVo entity) {
        return examRegistrationService.queryList(entity);
    }

    @ApiOperation("查询考试报名所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(ExamRegistrationVo entity) {
        return AjaxResult.success("查询成功", examRegistrationService.queryAll(entity));
    }

    @ApiOperation("导出考试报名列表")
    @PreAuthorize("@ss.hasPermi('examation:examRegistration:export')")
    @Log(title = "考试报名", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExamRegistrationVo entity) {
        List<ExamRegistrationVo> list = examRegistrationService.queryAll(entity);
        ExcelUtil<ExamRegistrationVo> util = new ExcelUtil<>(ExamRegistrationVo.class);
        util.exportExcel(response, list, "考试报名数据");
    }

    @ApiOperation("获取考试报名详细信息")
    @PreAuthorize("@ss.hasPermi('examation:examRegistration:query')")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success("查询成功", examRegistrationService.queryById(id));
    }

    @ApiOperation("新增考试报名")
    @PreAuthorize("@ss.hasPermi('examation:examRegistration:add')")
    @Log(title = "考试报名", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody ExamRegistrationVo entity) {
        return toAjax(examRegistrationService.save(entity));
    }

    @ApiOperation("修改考试报名")
    @PreAuthorize("@ss.hasPermi('examation:examRegistration:edit')")
    @Log(title = "考试报名", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody ExamRegistrationVo entity) {
        return toAjax(examRegistrationService.updateById(entity));
    }

    @ApiOperation("删除考试报名")
    @PreAuthorize("@ss.hasPermi('examation:examRegistration:remove')")
    @Log(title = "考试报名", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(examRegistrationService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    @ApiOperation("当前用户报名考试")
    @Log(title = "考试报名", businessType = BusinessType.INSERT)
    @PostMapping("/register")
    public AjaxResult register(@RequestBody ExamRegistrationDto dto) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = getUserId();
            boolean result = examRegistrationService.registerExam(dto.getExamId(), dto.getVenueId(), currentUserId);
            return result ? AjaxResult.success("报名成功") : AjaxResult.error("报名失败");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("替其他用户报名考试")
    @Log(title = "考试报名", businessType = BusinessType.INSERT)
    @PostMapping("/registerForUser")
    public AjaxResult registerForUser(@RequestBody ExamRegistrationDto dto) {
        try {
            if (dto.getUserId() == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            boolean result = examRegistrationService.registerExam(dto.getExamId(), dto.getVenueId(), dto.getUserId());
            return result ? AjaxResult.success("报名成功") : AjaxResult.error("报名失败");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("查询报名人员列表")
    @GetMapping("/registrationUsers")
    public AjaxResult getRegistrationUsers(
            @RequestParam("examId") Long examId,
            @RequestParam(value = "venueId", required = false) Long venueId) {
        try {
            List<ExamRegistrationUserVo> users = examRegistrationService.queryRegistrationUsers(examId, venueId);
            return AjaxResult.success("查询成功", users);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("根据考试ID和考试时间ID查询报名人员列表")
    @GetMapping("/registrationUsersBySchedule")
    public TableDataInfo<ExamRegistrationUserVo> getRegistrationUsersBySchedule(
            @RequestParam("examId") Long examId,
            @RequestParam("scheduleId") Long scheduleId) {
        return examRegistrationService.queryRegistrationUsersBySchedulePage(examId, scheduleId);
    }

    @ApiOperation("当前用户报名考试（基于考试时间）")
    @Log(title = "考试报名", businessType = BusinessType.INSERT)
    @PostMapping("/registerBySchedule")
    public AjaxResult registerBySchedule(@RequestBody ExamRegistrationDto dto) {
        try {
            // 验证必要参数
            if (dto.getExamId() == null) {
                return AjaxResult.error("考试ID不能为空");
            }
            if (dto.getScheduleId() == null) {
                return AjaxResult.error("考试时间ID不能为空");
            }
            
            // 获取当前登录用户ID
            Long currentUserId = getUserId();
            boolean result = examRegistrationService.registerExamBySchedule(dto.getExamId(), dto.getScheduleId(), currentUserId);
            return result ? AjaxResult.success("报名成功") : AjaxResult.error("报名失败");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    
}
